<template>
  <div class="echarts-container" :style="chartStyle">
    <div class="chart-header" v-if="title || showRefresh">
      <h3 class="chart-title" v-if="title">{{ title }}</h3>
      <div class="chart-actions" v-if="showRefresh">
        <el-button 
          size="small" 
          type="primary" 
          circle 
          :icon="Refresh" 
          @click="handleRefresh"
          :loading="refreshing"
          class="refresh-btn"
        />
      </div>
    </div>
    
    <div class="chart-content">
      <div v-if="loading" class="chart-loading">
        <el-skeleton animation="pulse" :rows="1" class="loading-skeleton" />
      </div>
      <div 
        v-show="!loading" 
        ref="chartRef" 
        class="chart"
        :style="{ width: '100%', height: '100%' }"
      ></div>
      <div v-if="error && !loading" class="chart-error">
        <el-empty description="数据加载失败" :image-size="100">
          <el-button size="small" type="primary" @click="$emit('refresh')">重新加载</el-button>
        </el-empty>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { Refresh } from '@element-plus/icons-vue';

// 组件参数
const props = defineProps({
  width: {
    type: [String, Number],
    default: '100%'
  },
  height: {
    type: [String, Number],
    default: '400px'
  },
  options: {
    type: Object,
    default: () => ({})
  },
  autoResize: {
    type: Boolean,
    default: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  title: {
    type: String,
    default: ''
  },
  showRefresh: {
    type: Boolean,
    default: false
  },
  error: {
    type: Boolean,
    default: false
  }
});

// 事件定义
const emit = defineEmits(['chart-mounted', 'chart-resized', 'refresh', 'chart-click']);

// 图表引用
const chartRef = ref(null);
let chartInstance = null;
let resizeObserver = null;
const refreshing = ref(false);

// 计算图表样式
const chartStyle = {
  width: typeof props.width === 'number' ? `${props.width}px` : props.width,
  height: typeof props.height === 'number' ? `${props.height}px` : props.height
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  
  // 销毁已存在的图表实例
  if (chartInstance) {
    chartInstance.dispose();
  }
  
  // 创建新的图表实例
  chartInstance = echarts.init(chartRef.value, 'light');
  
  // 设置默认配置
  const defaultOptions = {
    backgroundColor: 'transparent',
    textStyle: {
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif'
    },
    animation: true,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  };
  
  // 确保配置安全，处理yAxis和series配置问题
  const safeOptions = { ...props.options };
  
  // 确保yAxis存在且为数组
  if (!safeOptions.yAxis) {
    safeOptions.yAxis = [{ type: 'value' }];
  } else if (!Array.isArray(safeOptions.yAxis)) {
    safeOptions.yAxis = [safeOptions.yAxis];
  }
  
  // 确保series配置正确
  if (safeOptions.series) {
    safeOptions.series = safeOptions.series.map((series, index) => ({
      ...series,
      yAxisIndex: series.yAxisIndex ?? 0, // 确保每个系列都有yAxisIndex
      animationDelay: (idx) => idx * 100,
      emphasis: {
        ...series.emphasis,
        scale: true,
        scaleSize: 5,
        focus: 'series'
      }
    }));
  } else {
    safeOptions.series = [];
  }
  
  // 合并默认配置和用户配置
  const mergedOptions = {
    ...defaultOptions,
    ...safeOptions,
    xAxis: safeOptions.xAxis ? { ...defaultOptions.xAxis, ...safeOptions.xAxis } : defaultOptions.xAxis,
    yAxis: safeOptions.yAxis
  };
  
  // 设置主题和配置
  chartInstance.setOption(mergedOptions, true);
  
  // 添加图表事件监听
  chartInstance.on('click', (params) => {
    emit('chart-click', params);
  });
  
  // 触发图表挂载事件
  emit('chart-mounted', chartInstance);
  
  // 添加响应式监听
  if (props.autoResize && window.ResizeObserver) {
    setupResizeObserver();
  }
};

// 设置尺寸变化监听
const setupResizeObserver = () => {
  if ('ResizeObserver' in window && chartRef.value) {
    resizeObserver = new ResizeObserver(() => {
      if (chartInstance) {
        chartInstance.resize();
        emit('chart-resized');
      }
    });
    resizeObserver.observe(chartRef.value);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize();
    emit('chart-resized');
  }
};

// 处理刷新
const handleRefresh = async () => {
  refreshing.value = true;
  emit('refresh');
  
  // 等待刷新完成后重置状态
  setTimeout(() => {
    refreshing.value = false;
  }, 1000);
};

// 监听配置变化
watch(() => props.options, (newOptions) => {
  if (chartInstance) {
    chartInstance.setOption(newOptions, true);
  }
}, { deep: true });

// 监听加载状态变化
watch(() => props.loading, (loading) => {
  if (chartInstance) {
    if (loading) {
      chartInstance.showLoading && chartInstance.showLoading({ 
        text: '加载中...',
        color: '#409eff',
        textColor: '#303133',
        maskColor: 'rgba(255, 255, 255, 0.8)',
        zlevel: 0
      });
    } else {
      chartInstance.hideLoading && chartInstance.hideLoading();
    }
  }
});

// 暴露方法给父组件
const chartMethods = {
  refresh: () => {
    nextTick(() => {
      setTimeout(() => {
        initChart();
      }, 100);
    });
  },
  getInstance: () => chartInstance,
  resize: () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  },
  updateChart: (options) => {
    if (chartInstance && options) {
      chartInstance.setOption(options, true);
    }
  },
  clearChart: () => {
    if (resizeObserver) {
      resizeObserver.disconnect();
      resizeObserver = null;
    }
    
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
  }
};

defineExpose(chartMethods);

// 组件生命周期
onMounted(() => {
  nextTick(() => {
    // 确保DOM元素有正确的宽高后再初始化
    setTimeout(() => {
      initChart();
    }, 100);
  });
  
  // 窗口大小变化监听（备用方案）
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  // 清理资源
  if (resizeObserver) {
    resizeObserver.disconnect();
  }
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.echarts-container {
  position: relative;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
  overflow: hidden;
}

.echarts-container:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
  background: #fafafa;
}

.chart-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.chart-actions {
  display: flex;
  gap: 8px;
}

.refresh-btn {
  min-width: 32px;
  width: 32px;
  height: 32px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.refresh-btn:hover {
  transform: scale(1.1);
  transition: transform 0.2s ease;
}

.chart-content {
  position: relative;
  padding: 20px;
  width: 100%;
  height: calc(100% - 64px); /* 减去header高度 */
  min-height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 260px;
}

.chart-loading {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.loading-skeleton {
  width: 100%;
  height: 100%;
  min-height: 260px;
  border-radius: 8px;
}

.chart-error {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-header {
    padding: 12px 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .chart-content {
    padding: 16px;
    height: calc(100% - 84px); /* 调整高度计算 */
    min-height: 250px;
  }
  
  .chart-title {
    font-size: 14px;
  }
  
  .chart {
    min-height: 220px;
  }
}

@media (max-width: 480px) {
  .echarts-container {
    border-radius: 8px;
  }
  
  .chart-content {
    padding: 12px;
    min-height: 200px;
  }
  
  .chart {
    min-height: 180px;
  }
}
</style>